package com.remoter.monitor.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.stereotype.Service;

import com.remoter.api.configure.IConfiguration;
import com.remoter.api.configure.support.AbstractConfiguration;
import com.remoter.api.context.support.Exporter;
import com.remoter.api.context.support.Importer;
import com.remoter.api.extension.support.ExtensionLoader;
import com.remoter.api.registry.IRegistry;
import com.remoter.api.util.Final;
import com.remoter.monitor.service.IManagementService;

@Service
public class ManagementServiceImpl implements IManagementService{
	
	private IRegistry registry;
	
	@PostConstruct
	@Override
	public void start(){
		IConfiguration configuration = AbstractConfiguration.getConfiguration();
		this.registry = ExtensionLoader.getService(IRegistry.class,configuration.getOption(Final.O_SERVER_REGISTRY));
	}

	@PreDestroy
	@Override
	public void close(){
		if(null != this.registry){
			this.registry.close();
		}
	}

	@Override
	public List<String> hosts(){
		List<String> result = new ArrayList<String>();
		List<Exporter> exporters = this.registry.exporters();
		List<Importer> importers = this.registry.importers();
		for(Exporter exporter : exporters){
			String path = String.format("%s:%s",exporter.getHost(),exporter.getPort());
			if(result.contains(path)){
				continue;
			}
			result.add(path);
		}
		for(Importer importer : importers){
			String path = String.format("%s:%s",importer.getHost(),importer.getPort());
			if(result.contains(path)){
				continue;
			}
			result.add(path);
		}
		return result;
	}
	
}